package com.xiaotu.aop;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xiaotu.common.ResponseBase;
import com.xiaotu.common.RsponseStatus;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author zhangxiao
 * @create 2021-01-17 14:14
 */
@Aspect
@Component
public class ResponseAspect {

    public static final Logger LOGGER = LoggerFactory.getLogger(ResponseAspect.class);

    //抽取公共的切入点表达式
    //1.本类引用
    //2.其他的切面引用
    //@Pointcut("execution(public * com.wzzx.login.LoginController.*(..))")
    //@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    @Pointcut("execution(public * com.xiaotu..*Controller.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public ResponseBase responseStatus(ProceedingJoinPoint joinPoint) {
        Object data = null;
        Integer status = RsponseStatus.HTTP_RES_CODE_200;
        String msg = "请求成功";
        try {
            data = joinPoint.proceed();
        }catch (TokenExpiredException e){
            LOGGER.error(e.getMessage(), e);
            status = RsponseStatus.HTTP_RES_CODE_422;
            msg = e.getMessage();
        }catch (IllegalArgumentException e){
            LOGGER.error(e.getMessage(), e);
            status = RsponseStatus.HTTP_RES_CODE_406;
            msg = e.getMessage();
        }catch (Throwable e) {
            LOGGER.error(e.getMessage(), e);
            status = RsponseStatus.HTTP_RES_CODE_500;
            msg = "未知异常，请求失败！";
        }
        return new ResponseBase(status,msg,data);
    }


}
